var criteria = 
{ Name: "ESG Risk Rating", Level2: [
    { Name: "Material E&S Issues", Level3: [
        { Name: "Event Name", Level4: [{ Name: "Event Name", CriteriaEntityField: "Event Name", IsScreenable: false, CriteriaType: 6},
                                       { Name: "Event Category", CriteriaEntityField: "Event Category", IsScreenable: false, CriteriaType: 25}] },
        { Name: "ESG Risk Rating", Level4: [{ Name: "ESG Risk Rating", CriteriaEntityField: "ESG Risk Rating", IsScreenable: true, CriteriaType: 6, MaxValue: 20  }, 
                                              { Name: "Weight", CriteriaEntityField: "Weight", IsScreenable: false, CriteriaType: 6}] },
        { Name: "Exposure Score", Level4: [{ Name: "Exposure Score", CriteriaEntityField: "Exposure Score", IsScreenable: true, CriteriaType: 6, MaxValue: 20  }] },
        { Name: "Managed Risk", Level4: [{ Name: "Managed Risk", CriteriaEntityField: "Managed Risk", IsScreenable: true, CriteriaType: 6, MaxValue: 20  }] }
    ]}
]};

function uuid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }
    return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
}

function HexToBase64(hex) {
    var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var base64 = "";
    var group;
    for (var i = 0; i < 30; i += 6) {
        group = parseInt(hex.substr(i, 6), 16);
        base64 += base64Digits[(group >> 18) & 0x3f];
        base64 += base64Digits[(group >> 12) & 0x3f];
        base64 += base64Digits[(group >> 6) & 0x3f];
        base64 += base64Digits[group & 0x3f];
    }
    group = parseInt(hex.substr(30, 2), 16);
    base64 += base64Digits[(group >> 2) & 0x3f];
    base64 += base64Digits[(group << 4) & 0x3f];
    base64 += "==";
    return base64;
}

function NUUID(uuid) {
    var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
    var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
    var b = hex.substr(10, 2) + hex.substr(8, 2);
    var c = hex.substr(14, 2) + hex.substr(12, 2);
    var d = hex.substr(16, 16);
    hex = a + b + c + d;
    var base64 = HexToBase64(hex);
    return new BinData(3, base64);
}

function processLevel1(criteria) {
    if (!db.CriteriaLevel1.findOne({ Name: criteria.Name })) {
        db.CriteriaLevel1.insert({
            _id: NUUID(uuid()),
            Name: criteria.Name,
            ShortName: 'RiskRatings',
            Order: NumberInt(15)
        });
    }
    var criteriaLevel1Id = db.CriteriaLevel1.findOne({ Name: criteria.Name })._id;
    criteria.Level2.forEach(function (criteria, index) {
        processLevel2(criteriaLevel1Id, criteria, index);
    });
}

function processLevel2(criteriaLevel1Id, criteria, index) {
    if (!db.CriteriaLevel2.findOne({ Name: criteria.Name })) {
        db.CriteriaLevel2.insert({
            _id: NUUID(uuid()),
            CriteriaLevel1Id: criteriaLevel1Id,
            UniverseFeature: NumberInt(18),
            Name: criteria.Name,
            ShortName: 'RiskRatings',
            Order: NumberInt(3)
        });
    }
    var criteriaLevel2 = db.CriteriaLevel2.findOne({ Name: criteria.Name });
    var criteriaLevel2Id = criteriaLevel2._id;
    var IdioNo = 5;
    var IdioIndex = 1;
    var currentIndex = db.CriteriaLevel3.find({CriteriaLevel2Id: criteriaLevel2Id }).count()
    while(IdioNo>0)
    {
        criteria.Level3.forEach(function (criteria, index) {
            processLevel3(criteriaLevel2Id, criteria, IdioIndex, currentIndex + index + 1);
        });
        IdioNo = IdioNo - 1;
        IdioIndex = IdioIndex + 1;
    }
}

function processLevel3(criteriaLevel2Id, criteria, IdioIndex, index) {
    if (!db.CriteriaLevel3.findOne({ Name: criteria.Name, CriteriaLevel2Id: criteriaLevel2Id, Category: "Idiosyncratic Issue "+IdioIndex })) 
    {
        db.CriteriaLevel3.insert({
            _id: NUUID(uuid()),
            Name: criteria.Name,
            ShortName: criteria.Name,
            Order: NumberInt(index),
            CriteriaLevel2Id: criteriaLevel2Id,
            Category: "Idiosyncratic Issue "+IdioIndex,
        });
    }
    var criteriaLevel3Id = db.CriteriaLevel3.findOne({ Name: criteria.Name, CriteriaLevel2Id: criteriaLevel2Id, Category: "Idiosyncratic Issue "+IdioIndex })._id;
    criteria.Level4.forEach(function (criteria) {
        processLevel4(criteriaLevel2Id, criteriaLevel3Id, criteria, IdioIndex, index);
    });
}

function processLevel4(criteriaLevel2Id, criteriaLevel3Id, criteria, IdioNo, index) {
    if (!db.TemplateCriteria.findOne({ Name: criteria.Name, CriteriaLevel2Id: criteriaLevel2Id })) {
        if(criteria.MaxValue)
        db.TemplateCriteria.insert({
            _id: NUUID(uuid()),
            Name: "Idiosyncratic Issue " + IdioNo + " - " + criteria.Name,
            CriteriaEntity: null,
            CriteriaEntityField: "Issue " + IdioNo + "-" + criteria.CriteriaEntityField,
            CriteriaType: NumberInt(criteria.CriteriaType),
            CriteriaLevel2Id: criteriaLevel2Id,
            CriteriaLevel3Id: criteriaLevel3Id,
            IsScreenable: criteria.IsScreenable,
            ResearchProducts: ["RiskRating"],
            GetsValueFromParent: true,
            HasFullRangeChart: criteria.HasFullRangeChart == false ? false : true,
            MaxValue: NumberInt(criteria.MaxValue),
       });
        else
        db.TemplateCriteria.insert({
            _id: NUUID(uuid()),
            Name: "Idiosyncratic Issue " + IdioNo + " - " + criteria.Name,
            CriteriaEntity: null,
            CriteriaEntityField: "Issue " + IdioNo + "-" + criteria.CriteriaEntityField,
            CriteriaType: NumberInt(criteria.CriteriaType),
            CriteriaLevel2Id: criteriaLevel2Id,
            CriteriaLevel3Id: criteriaLevel3Id,
            IsScreenable: criteria.IsScreenable,
            ResearchProducts: ["RiskRating"],
            GetsValueFromParent: true,
            HasFullRangeChart: criteria.HasFullRangeChart == false ? false : true,
       });
    }
}

processLevel1(criteria);    